package com.example.getfromservice.Activity;

import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import com.example.getfromservice.R;
import com.example.getfromservice.Category.Category;
import com.example.getfromservice.Category.CategoryDAO;
import com.example.getfromservice.Category.DataHandler;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;




public class SecondActivity extends Activity {

	private CategoryDAO datasource; 
	private Category category;
	private Bundle extras;
	private int[] info_from_main_activity ;
	private LongRunningAccept longRunningaccept = null;
	private boolean mDone = true;
	private HttpPost httppost;
	private HttpPut httpput;

	
	
//*********************************************** ONCREATE ****************************************
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        
        datasource = new CategoryDAO(this);
        datasource.open();
       
       
        extras = getIntent().getExtras();
        info_from_main_activity = extras.getIntArray("Info");
        

       if( info_from_main_activity[1] != 0 )
	        {      
	        	inputdata( info_from_main_activity[0] );
	        	
	        }

        
    }
   
//*********************************************** ISONLINE ****************************************

    public boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
       
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
           
        	return true;
        }
        
        return false;
    }
    
//*********************************************** INPUTDATA ***************************************    
  
    private void inputdata(int iD) {
		
    	EditText catname = (EditText) findViewById(R.id.etcatname);
    	
    	category = new Category();	
    	
    	if( !isOnline() ) 
    	{
    		
	    	category = datasource.selectCategoryfromDB(iD);
    	
	    	
	    	catname.setText(category.getName());
	    	
    	}
    	else if ( isOnline() )
    	{
    		DataHandler handler = new DataHandler(getApplicationContext());
    		ArrayList<Category> catlist = new ArrayList<Category>();
			catlist = handler.getData();
			
			for (Category cat : catlist) {
				
				if( cat.getID() == iD )
					{
						category = cat;
						break;
					}
			}
			
			catname.setText(category.getName());
			
    		
    	}
		
	}

  //************************************************* ONCLICK ****************************************    

	public void onClick(View v)
    {
    	switch(v.getId())
    	{
    		case R.id.ok : 
					    		{
						    			
						    			
						    			boolean needToCreate = false;
						    			
						     			if (longRunningaccept == null) {
						     			      needToCreate=true;
						     			} else {
						     				if (longRunningaccept.isDone()) {
						     					needToCreate=true;
	
						     					longRunningaccept = null;
						     				}
						     			}
						     			if (needToCreate) {
						     				longRunningaccept = new LongRunningAccept();
						     				longRunningaccept.execute();
						     			}
					    			
					    		}
			break;

    	}
    }
    
//*********************************************** ONRESUME ****************************************
	
    @Override
    protected void onResume() {
      datasource.open();
      super.onResume();
       
    }

 //*********************************************** ONPAUSE ***************************************    
    
    @Override
    protected void onPause() {
      datasource.close();
      super.onPause();
    }
 
 //*********************************************** ACCEPT ********************************************    
    
    private class LongRunningAccept extends AsyncTask<Void, Void, Integer> {

		boolean isDone() { return mDone; }

		@Override
		protected Integer doInBackground(Void... params) {
			
			EditText catname = (EditText) findViewById(R.id.etcatname);
			int id = datasource.getLastInsertId();
			category = new Category();
			String xml = null;
			
			HttpClient httpclient = new DefaultHttpClient();
			
			try{
			
					// 0 - new ; 1 - update
					if( isOnline() && info_from_main_activity[1] == 0 )
						{
								
								int last = info_from_main_activity[0]+1;
							    httppost = new HttpPost("http://10.0.2.2:8020/categoryservice/category/");
								
							    xml = "<Category><categoryId>"+last+"</categoryId><categoryName>"+catname.getText()+"</categoryName></Category>";
							    	    
							    httppost.addHeader("Content-Type", "application/xml");
							    	    
							    StringEntity se = new StringEntity(xml,HTTP.UTF_8);
							    httppost.setEntity(se);  
							    	    
							    se.setContentType("application/xml");
							    	    
							    // Execute HTTP Post Request
							    HttpResponse response = httpclient.execute(httppost);
							    Log.i("Respones",response.toString());
						    							
						}
					else if( isOnline() && info_from_main_activity[1] == 1 )
						{
								
								httpput = new HttpPut("http://10.0.2.2:8020/categoryservice/category/");
							    	
						    	xml = "<Category><categoryId>"+info_from_main_activity[0]+"</categoryId><categoryName>"+catname.getText()+"</categoryName></Category>";
				    	   
						    	httpput.addHeader("Content-Type", "application/xml");
						    	    	
						    	StringEntity se = new StringEntity(xml,HTTP.UTF_8);
						    	httpput.setEntity(se);  
			
						    	se.setContentType("application/xml");
						    	// Execute HTTP Post Request
						    	HttpResponse response = httpclient.execute(httpput);
						    	Log.i("Respones",response.toString());
															
						}
					else if( !isOnline() && info_from_main_activity[1] == 0 )
						{
							
								category.setID(id+1);
								category.setName(catname.getText().toString());
							
								category.setChanges(2);
								datasource.createCategory(category);
								
						}
					else if( !isOnline() && info_from_main_activity[1] == 1 )
						{
							
								category.setID(info_from_main_activity[0]);
								category.setName(catname.getText().toString());
							
								category.setChanges(1);
							
								Category tmp = datasource.selectCategoryfromDB(category.getID());
								category.setIdDB(tmp.getIdDB());
								datasource.updateCategoryinDB(category);
								
						}
				
				
			}catch(Exception pce) 
					{ 
		        
        				Log.e("LongRunningAccept", "PCE "+pce.getMessage()); 
        	
					}
			
	
				
				return 1;
			}

		protected void onPostExecute(Integer results) {
			if (results == 1) {

				finish();
			     		
			}
	
		}

	}
    
}
